package com.aiwiown.snackmq.broker.handler.console;

import com.aiwiown.snackmq.broker.auth.AuthorizationService;
import com.aiwiown.snackmq.cluster.metadata.MetadataManager;
import com.aiwiown.snackmq.cluster.raft.closeure.SnackMQApplyClosure;
import com.aiwiown.snackmq.common.handler.RequestContext;
import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageType;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DeleteRoleHandler extends AbstractLeaderRequiredConsoleHandler {

    public DeleteRoleHandler(MetadataManager metadataManager, AuthorizationService authorizationService) {
        super(metadataManager, authorizationService);
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.DELETE_ROLE_REQUEST;
    }

    @Override
    protected void doHandle(RequestContext ctx, Message request) {
        try {
            String roleName = request.getProperty("roleName");
            if (roleName == null || roleName.isEmpty()) {
                SnackMQApplyClosure.sendErrorResponse(ctx, request, "Role name is required.");
                return;
            }
            if ("admin-role".equals(roleName)) {
                SnackMQApplyClosure.sendErrorResponse(ctx, request, "Cannot delete default admin role.");
                return;
            }

            SnackMQApplyClosure closure = new SnackMQApplyClosure(request, ctx, null);
            metadataManager.deleteRole(roleName, closure);

        } catch (Exception e) {
            log.error("Error processing delete role request", e);
            SnackMQApplyClosure.sendErrorResponse(ctx, request, "Internal server error: " + e.getMessage());
        }
    }
}